/*
给你单链表的头指针 head 和两个整数 left 和 right ，其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点，返回 反转后的链表 。

输入：head = [1,2,3,4,5], left = 2, right = 4
输出：[1,4,3,2,5]
*/


struct ListNode {
    int val;
    struct ListNode *next;
};


struct ListNode* reverseBetween(struct ListNode* head, int left, int right){
    if(left >= right)
        return head;

    struct ListNode *left_index;
    struct ListNode *visit = head;

    int distance = right - left;

    while(left > 1)
    {
        visit = visit->next;
        left--;
    }
    left_index = visit;
    
    visit = visit->next;
    struct ListNode *right_node = visit->next;
    struct ListNode *temp;
    while(distance > 2)
    {
        temp = right_node->next;
        right_node->next = visit;
        visit = right_node;
        right_node = temp;
    }

    left_index->next->next = right_node;
    left_index->next = visit;

    return head;

}